<?php

namespace app\admin\controller\product;

use app\admin\model\Supplier;
use \app\admin\model\ProductLog;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\model\Relation;
use \app\admin\model\Category;
use function GuzzleHttp\Promise\is_settled;

/**
 * @ControllerAnnotation(title="product")
 */
class Product extends AdminController
{

    use \app\admin\traits\Curd;

    /**
     * 所有供应商 处理后的数组
     * @var array
     */
    protected $suppliers = [];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Product();

        /*
         * 获取所有供应商 处理后的数组
         */
        $this->suppliers = get_supplier_arr();

    }


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
//            dd($where);
            $count = $this->model
                ->withJoin(['category', 'supplier', 'rule'], 'LEFT')
//                ->with('suppliers')
                ->where($where)
                ->count();
            $list = $this->model
                ->withJoin(['category', 'supplier', 'rule'], 'LEFT')
                ->with(['suppliers'])
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();


            $supplier_id_arr = collection($list->toArray())->pluck("suppliers.*.supplier_id");
            $where_in = $supplier_id_arr->flatten()->unique()->toArray();


            $supplier_need_all = Supplier::whereIn('id', $where_in)->field('id,name')->select()->toArray();
            $supplier_name_arr = collection($supplier_need_all)->pluck('name', 'id')->toArray();


            $list = collection($list->toArray())->map(function ($item, $key) use ($supplier_name_arr) {

                if (isset($item['suppliers'])) {
                    foreach ($item['suppliers'] as $key => $v) {
                        $item['suppliers'][$key] = $supplier_name_arr[$v['supplier_id']];
                    }
                }

                return $item;

            })->toArray();

//            dd($list->toArray());
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="产品详情")
     */
    public function detail($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

//        dd($row);
//订单号 sales_number  下单时间     创建时间 create_time

// 派单时间 send_time   接单时间 accepted_time AI制作时间 ai_time

// 要求出货时间         实际出货时间     收货时间

//  要求入库时间 give_time 实际入库时间 real_give_time 是否超时 is_overtime

        $log = ProductLog::withJoin(['admin'], 'LEFT')
            ->where('product_id','=',$row->id)
            ->select()->toArray();

        $row = $row->toArray();
        $row['logs'] =$log;

        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="分配供应商")
     */
    public function distribute($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

        if ($this->request->isAjax()) {
            $post = $this->request->post();

            $rule = [
                'supplier_id|供应商' => 'require|integer',
            ];
            $this->validate($post, $rule);

            $save=true;
            if($post['supplier_id'] != $row->supplier_id){
                $admin = session("admin");
                $suppliers = $this->suppliers;
                $log=[
                    'product_id'=>$row->id,
                    'remark'=>$admin['username']."给此产品分配给了<".$suppliers[$post['supplier_id']].'>供应商',
                    'admin_id'=>$admin['id'],
                    'type'=>'供应商修改',
                ];

                $product_log = new ProductLog;
                $product_log->save($log);
                try {
                    $save = $row->save(['supplier_id' => $post['supplier_id']]);
                } catch (\Exception $e) {
                    $this->error('保存失败');
                }
            }

            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        $list = $this->model
            ->where('id',$id)
            ->with(['suppliers'])
            ->find();
        $suppliers = $list->getAttr('suppliers')->toArray();
        $supplier_id_arr = array_column($suppliers, 'supplier_id');

        $collect = collection($this->suppliers)->only($supplier_id_arr);
        $ret['supplier_list'] = $collect->toArray();
        $ret['supplier_id'] = $list->supplier_id;

        $this->assign('row', $ret);
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="作废")
     */
    public function cancel($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
//        cancel_reason 作废原因
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $admin = session("admin");
            $status =$this->request->post('status');
            if($status != 'on'){
                $row->status = "作废";
                $log=[
                    'product_id'=>$row->id,
                    'remark'=>$post['cancel_reason'],
                    'admin_id'=>$admin['id'],
                    'type'=>'作废',
                ];
                $product_log = new ProductLog;
                $product_log->save($log);
            }
            if($status == 'on'){

                $row->status = "生效";
                $log=[
                    'product_id'=>$row->id,
                    'remark'=>$post['cancel_reason'],
                    'admin_id'=>$admin['id'],
                    'type'=>'生效',
                ];
                $product_log = new ProductLog;
                $product_log->save($log);
            }

            try {
                $save = $row->save();
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }


        $this->assign('row', $row);
        return $this->fetch();
    }


    public function typelist()
    {

//        if ($this->request->isAjax()) {

            $list = Category::select()->toArray();
            $list=collection($list)->pluck('name','id')->toArray();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => 0,
                'data' => $list,
            ];
            return json($data);
//        }



    }



}